package com.xy.gateway.request.files;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xy.gateway.exception.GateWayException;
import com.xy.gateway.model.EpayGateSetting;
import com.xy.gateway.request.RequestHandler;
import com.xy.gateway.request.RequestHealper;
import com.xy.gateway.request.pub.RequestURLHandlerFactory;

public abstract class RequestFilesHandlerAbstract implements RequestHandler {
	protected HttpServletRequest req;
	protected HttpServletResponse res;
	private static int BUFFER_SIZE = 8096;

	public RequestFilesHandlerAbstract(HttpServletRequest req,
			HttpServletResponse res) {
		this.req = req;
		this.res = res;
	}

	public void doRequest() throws GateWayException {
		saveToFile();
	}

	public void saveToFile() throws GateWayException {
		try {
			FileOutputStream fos = null;
			BufferedInputStream bis = null;
			HttpURLConnection httpUrl = null;
			URL url = null;
			byte[] buf = new byte[BUFFER_SIZE];
			int size = 0;

			url = new URL(getURL());
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());

			fos = new FileOutputStream(getFileName());

			while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);

			fos.close();
			bis.close();
			httpUrl.disconnect();
		} catch (MalformedURLException e) {
			throw new GateWayException(e);
		} catch (FileNotFoundException e) {
			throw new GateWayException(e);
		} catch (IOException e) {
			throw new GateWayException(e);
		}
	}

	private String getFileName() {
		File dir = new File(EpayGateSetting.FILE_SAVE_DIR);
		if (!dir.exists()) {
			dir.mkdir();
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMDD");
		String d = sd.format(new Date());
		String sid = RequestHealper.getSidFromRequest(req);

		return dir + "/" + sid + "_" + d;
	}

	protected String getURL() {
		String url = RequestURLHandlerFactory.getInstance()
				.createRequestURLHandler(req).getURL();
		if (url.indexOf("?") == -1) {
			url = url + "?" + getRequestPara();
		}
		return url;
	}

	protected abstract String getRequestPara();
}
